package auth

import (
	"context"
	"fmt"
	"time"

	"oil-station-backend/internal/service"
	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
	"oil-station-backend/internal/model"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type WechatLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWechatLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WechatLoginLogic {
	return &WechatLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WechatLoginLogic) WechatLogin(req *types.WechatLoginReq) (resp *types.LoginResp, err error) {
	l.Infof("开始微信登录验证，code: %s", req.Code)

	// 初始化微信服务
	wechatService := service.NewWechatService()

	// 通过code获取openid
	wechatResp, err := wechatService.GetOpenId(req.Code)
	if err != nil {
		l.Errorf("获取微信openid失败: %v", err)
		return nil, fmt.Errorf("微信登录失败: %v", err)
	}

	l.Infof("微信登录成功，openid: %s", wechatResp.OpenId)

	// 查找或创建用户
	user, err := l.svcCtx.UserModel.FindByOpenId(wechatResp.OpenId)
	if err != nil {
		// 检查是否是记录不存在的错误
		if err == gorm.ErrRecordNotFound {
			// 用户不存在，创建新用户
			l.Infof("用户不存在，创建新用户，openid: %s", wechatResp.OpenId)
			
			newUser := &model.User{
				Username:  wechatResp.OpenId, // 使用openId作为username，确保唯一性
				OpenId:    wechatResp.OpenId,
				UnionId:   wechatResp.UnionId,
				NickName:  req.NickName,
				AvatarUrl: req.AvatarUrl,
				Gender:    req.Gender,
				City:      req.City,
				Province:  req.Province,
				Country:   req.Country,
				Name:      req.NickName, // 使用微信昵称作为姓名
				Role:      "user",       // 默认为普通用户
			}

			err = l.svcCtx.UserModel.Create(newUser)
			if err != nil {
				l.Errorf("创建用户失败: %v", err)
				return nil, fmt.Errorf("创建用户失败: %v", err)
			}

			user = newUser
			l.Infof("新用户创建成功，用户ID: %d", user.Id)
		} else {
			// 其他数据库错误
			l.Errorf("查找用户失败: %v", err)
			return nil, fmt.Errorf("查找用户失败: %v", err)
		}
	} else {
		// 用户存在，更新用户信息
		l.Infof("用户已存在，更新用户信息，用户ID: %d", user.Id)
		
		user.NickName = req.NickName
		user.AvatarUrl = req.AvatarUrl
		user.Gender = req.Gender
		user.City = req.City
		user.Province = req.Province
		user.Country = req.Country
		user.UnionId = wechatResp.UnionId

		err = l.svcCtx.UserModel.Update(user)
		if err != nil {
			l.Errorf("更新用户信息失败: %v", err)
			// 更新失败不影响登录，继续执行
		} else {
			l.Infof("用户信息更新成功")
		}
	}

	// 生成JWT令牌
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	claims := make(jwt.MapClaims)
	claims["exp"] = now + accessExpire
	claims["iat"] = now
	claims["id"] = user.Id
	claims["openId"] = user.OpenId
	claims["role"] = user.Role
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	tokenString, err := token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))
	if err != nil {
		l.Errorf("JWT令牌生成失败，用户ID: %d, 错误: %v", user.Id, err)
		return nil, err
	}

	l.Infof("微信登录成功，用户ID: %d, 角色: %s, 令牌已生成", user.Id, user.Role)

	return &types.LoginResp{
		Token: tokenString,
		UserInfo: types.User{
			Id:       user.Id,
			Username: user.OpenId, // 使用openId作为username
			Name:     user.Name,
			Role:     user.Role,
			Phone:    user.Phone,
		},
	}, nil
}